// created by noellynch
// May 14, 2009

package com.sceneworker.editors.glslshadereditor.glslcodepanel;

import java.awt.Event;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;

import javax.swing.AbstractAction;
import javax.swing.ActionMap;
import javax.swing.InputMap;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.KeyStroke;
import javax.swing.text.JTextComponent;

import net.miginfocom.swing.MigLayout;

import com.myjavautils.swing.MJSwingUtils;
import com.sceneworker.util.swing.sourcecompletionpanel.CompletionFrame;
import com.sceneworker.util.swing.sourcecompletionpanel.CompletionFrame.ICompletionHandler;

public class GLSLCodePanel extends JPanel {

	//private		JTextArea		mcl_codeText;
	private		GLSLFormattedTextPane		mcl_codeText;
	private		JScrollPane					mcl_scrollPane;
	
	public	GLSLCodePanel(String str_shader) {
		setLayout(new MigLayout("insets 5", "[grow, fill]"));
		mcl_codeText = new GLSLFormattedTextPane();
		//mcl_codeText.setTabSize(2);
		mcl_codeText.setTabs(2);
		mcl_scrollPane = new JScrollPane();
		
		mcl_codeText.setText(str_shader);
		
		InputMap		lcl_ipMap = mcl_codeText.getInputMap();
		ActionMap		lcl_actionMap = mcl_codeText.getActionMap();
		
		lcl_actionMap.put("SRC_POP", new SourceCompletionPopupActionForGLSLCodeArea(mcl_codeText));
		
		KeyStroke		lcl_pop = KeyStroke.getKeyStroke(KeyEvent.VK_SPACE, Event.CTRL_MASK);
		lcl_ipMap.put(lcl_pop, "SRC_POP");
		
		mcl_scrollPane.setViewportView(mcl_codeText);
		add(mcl_scrollPane, "w 100%, h 100%");
	}
	
	public	String	getShaderCode() {
		return mcl_codeText.getText();
	}
	
	public	void	format() {
		mcl_codeText.format();
	}
	
	public	void	setShaderCode(String str_code) {
		mcl_codeText.setText(str_code);
	}
	
	class	SourceCompletionPopupActionForGLSLCodeArea extends AbstractAction {
		public	GLSLFormattedTextPane		mcl_parentTextArea;
		
		public	SourceCompletionPopupActionForGLSLCodeArea(GLSLFormattedTextPane cl_par) {
			mcl_parentTextArea = cl_par;
		}
		
		public void actionPerformed(ActionEvent cl_e) {
			Point		lcl_pt = mcl_parentTextArea.getCaret().getMagicCaretPosition();
			int			li_modelOffset = mcl_parentTextArea.viewToModel(lcl_pt);
			
			String		lstr_keyWord = MJSwingUtils.getKeyWordFromTextComponent(mcl_parentTextArea);
			lstr_keyWord.trim();
				
			ICompletionHandler		lcl_handler = new ICompletionHandler() {

				public JTextComponent getTextComponent() {
					return mcl_parentTextArea;
				}

				public void insert(String str_s, int i_pos) {
					mcl_parentTextArea.insert(str_s, i_pos);
				}

				public void replaceRange(String str_s, int i_start, int i_end) {
					mcl_parentTextArea.replaceRange(str_s, i_start, i_end);
				}
				
			};
			CompletionFrame		lcl_frame = new CompletionFrame(lstr_keyWord, lcl_handler, GLSLKeyWordsArray.inst().getGLSLCompletionParts(), lcl_pt.x, lcl_pt.y);
			
		}
	}
	
	
	
	
}
